<!--院外协同经销商--新建订单--新建批发采购订单-->
<template>
  <div class="newwholesaleorders-box">
    <el-container class="newPurchase-box">
      <!-- 头部 -->
      <h3 class="title">基础信息</h3>
      <el-header
        height="auto"
        class="form-wrapper">
        <el-form
          :model="purchaseOrderInfo"
          :rules="rules"
          :inline="true"
          ref="purchaseOrderForm"
          label-width="130px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="供应商"
            prop="supplier">
            <el-select
              v-model="purchaseOrderInfo.supplier"
              :loading="supplierLoading"
              placeholder="请选择"
              @change="information"
            >
              <el-option
                v-for="(item, index) in supplierList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="收货地址"
            prop="storageAddress">
            <el-select
              v-model="purchaseOrderInfo.storageAddress"
              :loading="addressLoading"
              placeholder="请选择"
              @change="information"
            >
              <el-option
                v-for="(item, index) in addressList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input
              :disabled="true"
              v-model="purchaseOrderInfo.userName" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              :disabled="true"
              v-model='purchaseOrderInfo.userPhone'/>
          </el-form-item>
        </el-form>
      </el-header>
      <!-- 列表模块 -->
      <h3 class="title">采购产品</h3>
      <div
        v-if="isEmptyList"
        class="center-add-button-wrapper">
        <el-button
          type="primary"
          @click="openAddProductDialog">+ 添加产品</el-button>
      </div>
      <div
        v-if="!isEmptyList"
        class="top-add-button-wrapper">
        <div class="title-info">
          <span>已选择产品数量 : {{ computedCount }}</span>
          <span>品种数 :{{ computedSelectLength }}</span>
          <span class="order-total-amount">金额合计(元) : <span style="color:red;">
            {{ formatPrice(orderTotalAmount) }}
          </span></span>
        </div>
        <span class="add-button">
          <el-button
            type="primary"
            @click="openAddProductDialog"
            size="small">添加产品</el-button>
          <el-button
            type="button"
            @click="deleteOrderProductItem()"
            size="small">批量删除</el-button>
        </span>
      </div>
      <el-editable
        v-if="!isEmptyList"
        v-loading="tableLoading"
        :data="curPageList"
        height="400"
        :columns="purchaseOrderProductListColumns"
        @selection-change="handleSelectionChange"
      >
        <!-- 销售价格 -->
        <template
          slot="default-price"
          slot-scope="scope">
          <el-input-number
            :disabled="scope.row.isEdit"
            v-model="scope.row.price"
            :min="0"
            :max="9999999"
            class="num-box"
            size="mini"
            @change="changePrice(scope,$event)"
          />
          <el-button
            v-if="scope.row.isEdit"
            type="text"
            @click="scope.row.isEdit = false"
          >编辑</el-button
          >
          <el-button
            v-else
            type="text"
            @click="changePriceSbumit(scope,$event)"
          >确定</el-button
          >
        </template>
        <!-- 采购数量 -->
        <template
          slot="default-purchaseNum"
          slot-scope="scope">
          <el-input-number
            :disabled="scope.row.isEditNum"
            v-model="scope.row.purchaseNum"
            size="mini"
            :min="1"
            :max="9999999"
          />
          <el-button
            v-if="scope.row.isEditNum"
            type="text"
            @click="scope.row.isEditNum = false"
          >编辑</el-button
          >
          <el-button
            v-else
            type="text"
            @click="changeNumSbumit(scope,$event)"
          >确定</el-button
          >
        </template>
        <!-- 操作 -->
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="deleteOrderProductItem(scope)"
            type="text text-danger"
          >删除</el-button>
        </template>
      </el-editable>
      <!-- 选择采购产品/添加产品 -->
      <add-product-dialog
        :dialog-visible.sync="addProductDialogShow"
        title="选择采购产品"
        :query-url="getAuthItemCommonQuery"
        query-method="post"
        :extra-query="sCompanyQuery"
        :supplier-id="purchaseOrderInfo.supplier"
        :supplier-name="purchaseOrderInfo.companyName"
        :current-products="purchaseOrderProductList"
        @confirmDialog="addSelectionToProductList"
        @cancelDialog="cancelAddSelection"
        :type='dialogType'
      />
    </el-container>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { purchaseOrderProductListColumns } from './const'
import SearchForm from '@components/businesscomponents/search'
import ElEditable from '@components/el-editable'
import AddProductDialog from '@/moduleComponents/beforeSettle/hospitalSide/addProduct'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { computeRate, computeAdd, getFormatterPrice } from '@const/filter'
import {
  createPurchaseOrder,
  editPurchaseOrder,
  orderDetail
} from '@const/orderCenterApi'
import {
  hossynordercenterdeliverySixsave,
  getHospitalPurchaseOrderList,
  getAddressListAll,
  getHospitalCreateOrder,
  getHospitalPurchaseOrderItem,
  hossynPssPsOrderYyPssPsPurchaseOrdersave,
  YyPssPsPurchaseOrderUpdatePrice, // 编辑价格
  YyPssPsPurchaseOrderUpdateNumber, // 编辑数量
  YyPssPsPurchaseOrderPproductList, // 产品列表
  YyPssPsPurchaseOrderSaveOrder, // 提交
  YyPssPsPurchaseOrderDelProduct, // 删除产品
  YyPssPsPurchaseOrderAddOrder // 添加产品
} from '@const/beforeSettleApi'
import { partnerList, channelBusinessDownList } from '@const/authCenterApi'
import { getlistLinkedHospitalProduct } from '@const/productCenterV2Api'
import { getAuthItemCommonQuery } from '@const/productCenterApiV2'
import { formatPrice } from '@const/agencySaas'
import { cloneDeep, isObject, uniqBy, hasIn } from 'lodash'
export default {
  components: { ElEditable, SearchForm, AddProductDialog },
  data () {
    return {
      getlistLinkedHospitalProduct,
      getAuthItemCommonQuery,
      purchaseOrderProductListColumns, // 页面产品列表表头
      orderDetail: {},
      addProductDialogShow: false,
      providerList: [],
      providerLoading: false,
      addressList: [],
      supplierList: [], // 供应商
      addressLoading: false,
      supplierLoading: false,
      purchaseOrderInfo: {
        supplier: '',
        storageAddress: '',
        userName: '',
        userPhone: '',
        companyName: ''
      },
      Contacts: null,
      Contactnumber: null,
      purchaseOrderProductList: [],
      purchaseOrderProductTableList: [],
      rules: {
        storageAddress: [{ required: true, message: '请选择', trigger: 'change' }],
        supplier: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      tableLoading: false, // 这里的loading只有在扩展编辑订单功能之后才有用
      detailsId: this.$route.query.id || '',
      computedCount: 0,
      selectList: [],
      computedSelectLength: 0,
      orderTotalAmount: 0,
      dialogType: 'distributor',
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      curPageList: []
    }
  },
  computed: {
    ...mapState(['companyId', 'companyType', 'roleType']),
    isEmptyList () {
      return this.curPageList.length === 0
    },
    sCompanyQuery () {
      return {
        downEnterpriseId: this.companyId,
        upEnterpriseId: this.purchaseOrderInfo.sCompanyId
      }
    }
  },
  watch: {
    'purchaseOrderInfo.supplier' (val) {
      this.getProductList(val)
      this.supplierList.forEach((item) => {
        if (val === item.value) {
          this.purchaseOrderInfo.companyName = item.label
        }
      })
    }
  },
  mounted () {
    let obj = {
      type: 'btn',
      arr: [{ type: 'primary', val: '提交', handle: this.handleSubmit }]
    }
    this.$store.commit('changeLayoutHandle', obj)
    // 查询收货地址
    this.getAddressList()
    this.getBusinessList()// 供应商
  },
  methods: {
    computeRate,
    getFormatterPrice,
    formatPrice,
    changePrice (data, value) {
      let val = Number(value).toFixed(3)
      data.row.a = val
      data.row.salePrice = val
    },
    // 产品列表
    getProductList (id) {
      let supplierId = ''
      if (id) {
        supplierId = id
      } else {
        supplierId = this.purchaseOrderInfo.supplier
      }
      this.$axios({
        method: 'post',
        url: YyPssPsPurchaseOrderPproductList,
        data: { supplierId: supplierId }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            let data = hasIn(res, 'data.payload') ? res.data.payload : []
            if (data) {
              data.forEach(item => {
                item.isEdit = true
                item.isEditNum = true
              })
              this.curPageList = data
              this.computedCount = data[0].numCount
              this.computedSelectLength = data[0].prodTypeCount
              this.orderTotalAmount = data[0].orderTotalAmount
              this.totalElements = data[0].numCount
            }
          } else {
            this.$message({
              type: 'warning',
              message: '查询失败'
            })
          }
        })
        .catch(res => {
          console.log('res', res)
        })
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.getProductList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getProductList()
    },

    information (a) {
      this.addressList.forEach(item => {
        if (item.value === a) {
          this.purchaseOrderInfo.userName = item.Contacts
          this.purchaseOrderInfo.userPhone = item.Contactnumber
          this.purchaseOrderInfo.storageAddress = item.value
        }
      })
    },
    // 获取供应商列表
    getBusinessList () {
      this.$axios({
        method: 'get',
        url: channelBusinessDownList,
        params: {
          partnership: 'provider',
          registered: '2'
        }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            let data = hasIn(res, 'data.payload') ? res.data.payload : {}
            data.forEach((item) => {
              let obj = {
                value: item.companyId,
                label: item.companyName
              }
              this.supplierList.push(obj)
            })
          } else {
            this.$message({
              type: 'warning',
              message: '查询失败'
            })
          }
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '查询失败'
          })
        })
    },
    // 列表批量选择的回调
    handleSelectionChange (list) {
      this.selectList = list
    },
    getAddressList () {
      this.addressLoading = true
      this.$axios
        .$post(getAddressListAll, {
          // 断数据来源；1，医院端  2，配送商端'
          yp: 2
        })
        .then(res => {
          const list = isObject(res.payload.content) ? res.payload.content : []
          this.addressList = list.map(item => {
            let obj = {}
            obj = {
              value: item.id,
              label:
                item.province + item.city + item.area + item.detailedAddress,
              Contacts: item.userName,
              Contactnumber: item.userPhone
            }
            return obj
          })
        })
        .catch(e => {})
        .finally(() => {
          this.addressLoading = false
        })
    },
    openAddProductDialog () {
      if (!this.purchaseOrderInfo.supplier) {
        return this.$message.warning('请先选择供应商')
      }
      if (!this.purchaseOrderInfo.storageAddress) {
        return this.$message.warning('请先选择收货地址')
      }
      this.addProductDialogShow = true
    },
    addSelectionToProductList (selection) {
      if (!selection.length) {
        this.$message.warning('请选择产品')
        return
      }
      let ids = []
      selection.forEach((item) => {
        ids.push(item.id)
      })
      this.$axios({
        method: 'post',
        url: YyPssPsPurchaseOrderAddOrder,
        data: {
          ids: ids,
          supplierId: this.purchaseOrderInfo.supplier,
          supplierName: this.purchaseOrderInfo.companyName
        }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '添加成功' })
          } else {
            this.$message({
              type: 'warning',
              message: '添加失败'
            })
          }
          this.getProductList()
          this.$emit('confirmDialog')
        })
        .catch(res => {
          console.log('res335', res)
          this.$message({
            type: 'warning',
            message: '添加失败'
          })
        })
      this.getProductList()
    },
    // 重组数据 计算金额
    ProductList () {
      console.log(111)
    },
    cancelAddSelection () {
      this.addProductDialogShow = false
    },
    deleteOrderProductItem (data) {
      this.$confirm('此操作将删除产品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = []
        if (data && data !== undefined) {
          params.push(data.row.id)
        } else {
          if (!this.selectList.length) {
            this.$message({ type: 'warning', message: '请选择需要删除的产品' })
            return
          }
          this.selectList.forEach((item) => {
            params.push(item.id)
          })
        }
        this.$axios({
          method: 'post',
          url: YyPssPsPurchaseOrderDelProduct,
          data: { ids: params }
        })
          .then(res => {
            let code = hasIn(res, 'data.code') ? res.data.code : ''
            if (Number(code) === 0) {
              this.$message({ type: 'success', message: '删除成功' })
            } else {
              this.$message({
                type: 'warning',
                message: '删除失败'
              })
            }
            this.getProductList()
          })
          .catch(res => {
            this.$message({
              type: 'warning',
              message: '删除失败'
            })
          })
      })
    },
    handleSubmit () {
      this.createPurchaseOrder()
    },

    createPurchaseOrder () {
      this.$refs.purchaseOrderForm.validate(valid => {
        if (valid) {
          const receiveAddressName = this.addressList.filter(item => {
            return this.purchaseOrderInfo.storageAddress === item.value
          })[0].label
          if (this.isEmptyList) {
            return void this.$message({ type: 'warning', message: '请添加产品' })
          }
          const postData = {
            concatMan: this.purchaseOrderInfo.userName,
            concatPhone: this.purchaseOrderInfo.userPhone,
            receiveAddressId: this.purchaseOrderInfo.storageAddress,
            receiveAddressName: receiveAddressName,
            supplierId: this.purchaseOrderInfo.supplier,
            supplierName: this.purchaseOrderInfo.companyName
          }
          this.$axios
            .$post(YyPssPsPurchaseOrderSaveOrder, postData)
            .then(res => {
              if (res.code === '0') {
                this.$message({ type: 'success', message: '新增成功' })
                this.$router.push(
                  '/distributorSide/purchasingManagement/purchaseOrderTracking/wholesalePurchaseOrder'
                )
              }
            })
            .catch(e => {})
        }
      })
    },
    // 编辑价格
    changePriceSbumit (data, value) {
      data.row.isEdit = true
      this.$axios({
        method: 'post',
        url: YyPssPsPurchaseOrderUpdatePrice,
        data: {
          id: data.row.id,
          price: data.row.price
        }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '编辑成功' })
          } else {
            this.$message({
              type: 'warning',
              message: '编辑失败'
            })
          }
          this.getProductList()
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '编辑失败'
          })
        })
    },
    changeNumSbumit (data, value) {
      data.row.isEdit = true
      this.$axios({
        method: 'post',
        url: YyPssPsPurchaseOrderUpdateNumber,
        data: {
          id: data.row.id,
          purchaseNum: data.row.purchaseNum
        }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '编辑成功' })
          } else {
            this.$message({
              type: 'warning',
              message: '编辑失败'
            })
          }
          this.getProductList()
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '编辑失败'
          })
        })
    }
  }
}
</script>
<style lang='less'>
.newwholesaleorders-box {
  .upEnterpriseNameBox {
    font-size: 16px;
    font-weight: 600;
  }
  .newPurchase-box {
    height: 100%;
    overflow: auto;

    .form-wrapper {
      margin-top: 16px;
      margin-left: -56px;
      display: flex;
    }

    .title {
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }

    .top-add-button-wrapper {
      display: flex;
      margin: 24px 0;
      justify-content: space-between;
      .add-button {
        // flex: 1;
        margin-right: 16px;
      }
      .title-info {
        span {
          margin-right: 16px;
        }
      }
      .order-total-amount {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .center-add-button-wrapper {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 17px;
    }

    .edit-form {
      .btnBox {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        // background: pink;
        height: 50px;
      }

      .pagination {
        padding-top: 10px;
        display: flex;
        justify-content: flex-end;
        padding-right: 0;
      }
    }

    .demo-ruleForm {
      // display: flex;
      // width: 500px;

      .el-select {
        width: 100%;
      }
    }

    .ul-list {
      overflow: hidden;
      margin: 10px 0;

      li {
        list-style: none;
        float: left;
        margin-right: 30px;

        i {
          display: inline-block;
          width: 15px;
          height: 10px;
        }

        .auth {
          background: #e6a23c;
        }

        .part {
          background: #eee;
        }
      }
    }
  }
}
</style>
